﻿using System;
using System.Net;
using System.Linq;
using System.Net.Sockets;
using System.Threading;

namespace CloudReader.Net
{
    /// <summary>
    /// 为所有套接字提供完成端口操作，该层为IO操作层
    /// </summary>
    public class CloudReaderSocket
    {
        protected Socket m_socket;


        public CloudReaderSocket()
        {
            
            Init(ref m_socket);
        }

        #region 绑定端口

        protected string GetHostName()
        {
            var dns = Dns.GetHostName();
            return dns;
        }
        protected IPAddress[] GetLocalIPEndPoint()
        {
            return (from e in  Dns.GetHostAddresses(GetHostName()) where e.AddressFamily == AddressFamily.InterNetwork select e).ToArray();
        }
        protected void SetDefault(int port)
        {
            m_socket.Bind(new IPEndPoint( GetLocalIPEndPoint()[0], port));
        }
        protected void SetSocket(IPEndPoint ip)
        {
            m_socket.Bind(ip);
        }

        #endregion

        //初始化缓冲区以及对象池
        protected void Init(ref Socket s)
        {
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public Socket GetSocket() => m_socket;
    }
}
